var util = require('util.js')
var api = require('../config/api.js');
const app = getApp();

//新登录方法
function doLogin (e,that) {
  var logindetail = e.detail;
  var latitude = '';
  var longitude = '';
  console.log(logindetail)
  wx.getLocation({
    type: 'wgs84',
    success(res) {
      latitude = res.latitude
      longitude = res.longitude
      wx.getSetting({
        success(res) {
          console.log(res);

          if (
            res.authSetting['scope.userInfo'] != undefined
            &&
            !res.authSetting['scope.userInfo']
          ) {
            if (that.data.curruserauth == 0) {
              wx.showModal({
                title: '提示',
                content: "请打开获取用户信息权限",
                showCancel: false,
                success: function (res2) {
                  if (res2.confirm) {
                    that.toSetting();

                    /*that.setData({
                      lock: false
                    });*/
                  }
                }
              });

              return;
            }
          }

          //先获取token
          wx.showLoading({
            title: "正在登录"
          });

          util.post(api.fetchToken()).then(function (res) {
            if (res.access_token != '') {
              return Promise.resolve({
                access_token: res.access_token
              });
            }
          }).then(function (res) {
            //console.log("res:" + res.accesstoken);

            if (res.access_token != '') {
              that.setData({
                accesstoken: res.access_token
              });

              util.login().then((res2) => {
                //console.log("wxcode:" + res2);
                //console.log("access_token:" + that.data.accesstoken);

                let tokenurl = api.My_fetchOpenidUrl + "?access_token=" + that.data.accesstoken;
                return util.request(tokenurl, {
                  wxcode: res2
                }, 'POST');
              }).then((res) => {
                //console.log(res);

                if (res.code == 200) {
                  /*wx.showToast({
                    title: '微信登录成功',
                  })*/

                  wx.hideLoading();

                  //console.log("logininfo.userInfo.nickName:" + logininfo.userInfo.nickName);
                  // 存储用户信息到本地(展开)

                  let _nickname = logindetail.userInfo.nickName;
                  if (null != app.globalData.logininfo.userInfo) {
                    let tmpnickname = app.globalData.logininfo.userInfo.nickName;
                    if (null != tmpnickname || '' != tmpnickname) {
                      _nickname = tmpnickname;
                    }
                  }
                  let loginurl = api.My_doLogin + "?access_token=" + that.data.accesstoken;
                  util.request(loginurl, {
                    longitude: longitude,
                    latitude: latitude,
                    openid: res.result.openid,
                    avatarurl: logindetail.userInfo.avatarUrl,
                    avatarpath: logindetail.userInfo.avatarpath,
                    nickname: _nickname,
                    country: logindetail.userInfo.country,
                    gender: logindetail.userInfo.gender
                  }, 'POST').then((res2) => {
                    let logininfo = {
                      userInfo: logindetail.userInfo,
                      openid: res.result.openid,
                      sessionkey: res.result.session_key,
                      loginid: res2.result.loginid,
                      loginname: res2.result.loginname,
                      storeInfo: {},
                      homeInfo: {},
                      tags: [],
                    };
                    if (res2.result.id != '' && res2.result.id != null) {
                      logininfo.userInfo.id = res2.result.id;
                    }
                    if (res2.result.userId != '' && res2.result.userId != null) {
                      logininfo.userInfo.userId = res2.result.userId;
                    }
                    if (res2.result.province != '' && res2.result.province != null) {
                      logininfo.userInfo.province = res2.result.province;
                    }
                    if (res2.result.city != '' && res2.result.city != null) {
                      logininfo.userInfo.city = res2.result.city;
                    }
                    if (res2.result.avatarpath != '' && res2.result.avatarpath != null) {
                      logininfo.userInfo.avatarpath = res2.result.avatarpath;
                    }
                    if (res2.result.avatarip != '' && res2.result.avatarip != null) {
                      logininfo.userInfo.avatarip = res2.result.avatarip;
                    }
                    if (res2.result.storepath != '' && res2.result.storepath != null) {
                      logininfo.userInfo.storepath = res2.result.storepath;
                    }
                    if (res2.result.storeip != '' && res2.result.storeip != null) {
                      logininfo.userInfo.storeip = res2.result.storeip;
                    }
                    if (res2.result.storehbpath != '' && res2.result.storehbpath != null) {
                      logininfo.userInfo.storehbpath = res2.result.storehbpath;
                    }
                    if (res2.result.storehbip != '' && res2.result.storehbip != null) {
                      logininfo.userInfo.storehbip = res2.result.storehbip;
                    }
                    if (res2.result.backgroundpath != '' && res2.result.backgroundpath != null) {
                      logininfo.userInfo.backgroundpath = res2.result.backgroundpath;
                    }
                    if (res2.result.backgroundip != '' && res2.result.backgroundip != null) {
                      logininfo.userInfo.backgroundip = res2.result.backgroundip;
                    }
                    if (res2.result.nickname != '')
                      logininfo.userInfo.nickName = res2.result.nickname;
                    if (res2.result.mobile != '')
                      logininfo.userInfo.mobile = res2.result.mobile;
                    if (res2.result.storename != '')
                      logininfo.userInfo.storename = res2.result.storename;

                    if (null != res2.result.storeInfo) {
                      if (res2.result.storeInfo.addr != '')
                        logininfo.storeInfo.addr = res2.result.storeInfo.addr;
                      if (res2.result.storeInfo.address != '')
                        logininfo.storeInfo.address = res2.result.storeInfo.address;
                      if (res2.result.storeInfo.jobtitle != '')
                        logininfo.storeInfo.jobtitle = res2.result.storeInfo.jobtitle;
                      if (res2.result.storeInfo.mastername != '')
                        logininfo.storeInfo.mastername = res2.result.storeInfo.mastername;
                      if (res2.result.storeInfo.mobile != '')
                        logininfo.storeInfo.mobile = res2.result.storeInfo.mobile;
                      if (res2.result.storeInfo.storefullname != '')
                        logininfo.storeInfo.storefullname = res2.result.storeInfo.storefullname;
                      if (res2.result.storeInfo.zipcode != '')
                        logininfo.storeInfo.zipcode = res2.result.storeInfo.zipcode;
                      if (res2.result.storeInfo.storeremark != '')
                        logininfo.storeInfo.storeremark = res2.result.storeInfo.storeremark;
                      if (res2.result.storeInfo.latitude != '')
                        logininfo.storeInfo.latitude = res2.result.storeInfo.latitude;
                      if (res2.result.storeInfo.longitude != '')
                        logininfo.storeInfo.longitude = res2.result.storeInfo.longitude;
                      if (res2.result.storeInfo.address != '')
                        logininfo.storeInfo.address = res2.result.storeInfo.address;
                    }

                    if (null != res2.result.homeInfo) {
                      if (res2.result.homeInfo.intereststr != '')
                        logininfo.homeInfo.intereststr = res2.result.homeInfo.intereststr;
                      if (res2.result.homeInfo.signname != '')
                        logininfo.homeInfo.signname = res2.result.homeInfo.signname;
                      if (res2.result.homeInfo.wechat != '')
                        logininfo.homeInfo.wechat = res2.result.homeInfo.wechat;
                      if (res2.result.homeInfo.circleIntroduction != '')
                        logininfo.homeInfo.circleIntroduction = res2.result.homeInfo.circleIntroduction;
                      if (res2.result.homeInfo.addr != '')
                        logininfo.homeInfo.addr = res2.result.homeInfo.addr;
                      if (res2.result.homeInfo.birthday != '')
                        logininfo.homeInfo.birthday = res2.result.homeInfo.birthday;
                      if (res2.result.homeInfo.sex != null) {
                        logininfo.homeInfo.sex = res2.result.homeInfo.sex;
                        logininfo.homeInfo.sexname = logininfo.homeInfo.sex == 1 ? '男' : '女';
                      }
                      if (res2.result.homeInfo.knowledge != '')
                        logininfo.homeInfo.knowledge = res2.result.homeInfo.knowledge;
                      if (res2.result.homeInfo.trade != '')
                        logininfo.homeInfo.trade = res2.result.homeInfo.trade;
                      if (res2.result.homeInfo.job != '')
                        logininfo.homeInfo.job = res2.result.homeInfo.job;
                    }

                    wx.setStorage({
                      key: 'logininfo',
                      data: logininfo
                    })

                    that.setData({
                      logininfo: logininfo
                    });
                    app.globalData.logininfo = logininfo;
                    that.onLoad();
                    that.onShow();
                  }).catch((err) => {
                    wx.hideLoading();

                    console.log(err);
                    console.log("保存信息错误!");
                  });
                }
              }).catch((err) => {
                wx.hideLoading();

                console.log(err);
              })
            }
            else {
              console.log("error accesstoken!");
            }
          }).catch((err) => {
            wx.hideLoading();

            console.log(err);
          });

          //that.data.lock = !that.data.lock
          // 如果没有登录，登录按钮操作
          //if (that.data.lock) {
          /*wx.showLoading({
            title: "正在登录"
          });*/
          //console.log("accesstoken:" + accesstoken);



          //} else {
          /*wx.showModal({
            title: "确认退出?",
            content: "确认退出吗?",
            success: (res2) => {
              if (res2.confirm) {
                //console.log("确定")
                // 退出登录则移除本地用户信息
                wx.removeStorageSync('userInfo');
                wx.removeStorageSync('driverMobile');
                that.setData({
                  userInfo: {
                    avatarUrl: "",
                    nickName: "未登录"
                  },
                  bType: "primary",
                  actionText: "登录",
  
                  phoneNumber: "",
                  mobiletip: "获取手机号,才能使用定位",
                  mobiletip2: "",
                  mobiletip3: "",
                  drivermobile: "",
                  mobileclass: "mobileclass_red"
                });
              } else {
                //console.log("cancel")
                that.setData({
                  lock: true
                })
              }
            }
          })*/
          //}
        }
      });
    },
    fail: function () {
      wx.showToast({
        title: '获取位置失败',
        icon: "none",
        duration: 2000
      })
    }
  })
  //判断是否有登录权限
  if (latitude != null && latitude!=''){
  
}
}

module.exports = {
  doLogin: doLogin
};